﻿using System;
using System.Collections.Generic;
using Kimgwajang.MidnightPeach.Properties;

namespace Kimgwajang.MidnightPeach.Utilities
{
    public class HistoryQueue
    {
        private readonly Queue<string> _queue = new Queue<string>(Settings.Default.MaxHistoryItem);

        public void Enqueue(string history)
        {
            if (_queue.Contains(history))
                return;

            _queue.Enqueue(history);

            if (_queue.Count > Settings.Default.MaxHistoryItem)
                _queue.Dequeue();

            OnEnqueued(ToArray());
        }

        public override string ToString()
        {
            return string.Join("|", _queue.ToArray());
        }

        public void Load(string text)
        {
            string[] tokens = text.Split('|');
            foreach (var token in tokens)
                _queue.Enqueue(token);

            OnEnqueued(ToArray());
        }

        public string[] ToArray()
        {
            return _queue.ToArray();
        }

        public string LastItem
        {
            get
            {
                var array = ToArray();
                return array[array.Length - 1];
            }
        }

        #region Enqueued event things
        public event EventHandler<EnqueuedEventArgs> Enqueued;

        protected virtual void OnEnqueued(EnqueuedEventArgs e)
        {
            if (Enqueued != null)
                Enqueued(this, e);
        }

        protected virtual void OnEnqueued(string[] histories)
        {
            if (Enqueued != null)
                Enqueued(this, new EnqueuedEventArgs(histories));
        }

        public class EnqueuedEventArgs : EventArgs
        {
            public string[] Histories { get; set; }

            public EnqueuedEventArgs(string[] histories)
            {
                Histories = histories;
            }
        }
        #endregion
    }
}